import request from "../apis/request";
import { MemberType } from "../components/Member";

export interface LoginObject {
    username: string,
    password: string,
}

/**
 * 用户登录token解析类
 * 单例
 */
class Authencation {
    // 单例对象
    private static instance: Authencation | null = null
    // 存储token
    token: string | null = null
    // 存储根据token获取的用户信息
    member: MemberType | undefined = undefined
    message: string | null = null

    private constructor() {
        // super(props)

        this.getToken()
    }

    // 单例实现
    static getInstance(): Authencation {
        if (!Authencation.instance) {
            Authencation.instance = new Authencation()
        }
        return Authencation.instance
    }

    setToken(token: string) {
        this.token = token
        localStorage.setItem('token', token)
        document.cookie = "token=Bearer " + token;
        // console.log('token', this.token)
        return this
    }

    getToken() {
        this.token = localStorage.getItem('token')
        // console.log('token', this.token)
        return this.token
    }

    setMember(member?: MemberType) {
        this.member = member
        localStorage.setItem('member', JSON.stringify(this.member))
        return this
    }

    getMember() {
        if(!this.member) {
            const member = localStorage.getItem('member')
            if (member) {
                this.member = JSON.parse(member || '');
            }
        }
        return this.member
    }

    logined() {
        if(!this.getToken()) {
            return Promise.reject(new Error('token empty'));
        }
        return this.tokenAvailable()
    }

    tokenAvailable() {
        return request.post('/direct/token-validate').then(() => true).catch((error) => {
            // console.log('token expired');
            // this.setToken('')
            // this.setMember()
            // throw error
            // wait for loading
            // window.location.href = '/login'
            return Promise.reject(error)
        })
    }

    login(data: LoginObject) {
        return request.post('/direct/login', data)
            .then((response: any) => {
                const { token, member } = response || {};
                if(!token) {
                    return Promise.reject(new Error('login failed'));
                }
                console.log('login', token, member);
                this.setToken(token)
                this.setMember(member)
                return this.member
            })
    }

    logout() {
        this.setToken('')
        // if(!this.setToken('')) {
        //     console.log('token set failed')
        //     console.log(this.getToken())
        //     return false
        // }
        return true
    }

    error(message?: string): string | null {
        if (message) {
            this.message = message
        }
        return this.message
    }

    /**
     * 请求头配置
     * @return object
     */
    header() {
        return {
            Authorization: this.getToken()
        }
    }
}

export default Authencation.getInstance()